from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet

from meiduo_admin.order.order_serializers import OrderSerializer, OrderRetrieveSerializer
from orders.models import OrderInfo
from meiduo_admin.user.my_pagination import MyNumberPagination


class OrderViewSet(ReadOnlyModelViewSet):
    pagination_class = MyNumberPagination

    # serializer_class = OrderSerializer
    # queryset = OrderInfo.objects.all()

    def get_queryset(self):
        keyword = self.request.query_params.get("keyword")
        if not keyword:
            queryset = OrderInfo.objects.all()
        else:
            queryset = OrderInfo.objects.filter(order_id__contains=keyword).all()
        return queryset

    def get_serializer_class(self):
        if self.action == 'list':
            return OrderSerializer
        else:
            return OrderRetrieveSerializer

    @action(methods=["put"], detail=True)  # 生成路由的格式: orders/pk/status
    def status(self, request, *args, **kwargs):
        # 1,获取参数
        status1 = request.data.get("status")
        order = self.get_object()

        # 2,校验参数
        if not status1:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 3,数据入库
        order.status = status1
        order.save()

        # 4,返回响应
        return Response(status=status.HTTP_200_OK)
